Step 26: Refactor

We don't want to interact with the production database when testing our endpoints. There are many reasons for that, from the risk of corrupting the data to impending app function (at production) and other functional or security concerns. So instead, we want to create a dedicated test database or mock the database. The approach I’ll take here is to use a separate test database.

Let’s update the src/data/db.js file so the connect function takes the URI as a parameter:

import mongoose from "mongoose";

const option = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

export function connect(URI) {
  mongoose.connect(URI, option);

  mongoose.connection.on("error", (err) => {
    console.log("Could not connect to MongoDB");
    console.log(err);
  });

  mongoose.connection.on("open", () => {
    console.log("Connected to MongoDB!");
  });
}

Next, update the src/index.js and remove the part where we import and connect to the database:

import express from "express";
import bookmarks from "./routes/bookmarks.js";

const app = express();

app.use(express.json());

app.get("/", (req, res) => {
  res.send("Welcome to the Bookmark API!");
});

app.use(bookmarks);

export default app;

Instead we will import and connect to database in server.js:

import app from "./src/index.js";
import * as db from "./src/data/db.js";

db.connect(process.env.DB_URI);
const PORT = 3000;

app.listen(PORT, () => {
  console.log(`Bookmark API at http://localhost:${PORT}/`);
});

Run the app and make sure everything works as expected! Then, save and commit all changes.